package com.lincoln.framework.common;

import com.lincoln.framework.utils.FrameworkLogger;
import com.lincoln.framework.utils.StringUtilsEx;
import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 处理api返回数据
 */
public class ApiMessageHandler {

	private static FrameworkLogger logger = FrameworkLogger.initFrameworkLogger(FrameworkLogger.class);

	private HttpServletRequest request;

	private HttpServletResponse response;

	/**
	 * 构造函数
	 * 
	 * @param request
	 * @param response
	 */
	public ApiMessageHandler(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
	}
	
	/**
	 * ajax调用消息返回
	 * 
	 * @param response
	 * @param message
	 * @param hasError
	 * @param extData
	 * @throws IOException
	 */
	public void returnData(String msg, Object dataJson) {
		JSONObject object = new JSONObject();

		object.put("code", ApiCode.SYSTEM_ERROR);
		object.put("msg", msg);
		object.put("data", StringUtilsEx.getJsonString(dataJson));
		this.response.setCharacterEncoding("utf-8");
		this.response.setContentType("application/json; charset=UTF-8");

		PrintWriter printWriter = null;
		try {
			printWriter = this.response.getWriter();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return;
		}
		printWriter.write(object.toString());
		printWriter.flush();
		printWriter.close();
		logger.log(object.toString());
	}

	/**
	 * ajax调用消息返回
	 * 
	 * @param response
	 * @param message
	 * @param hasError
	 * @param extData
	 * @throws IOException
	 */
	public void returnData(int apiCode, Object dataJson) {
		JSONObject object = new JSONObject();

		object.put("code", apiCode);
		object.put("msg", ApiCode.CODE_MAP.get(apiCode));
		object.put("data", StringUtilsEx.getJsonString(dataJson));
		this.response.setCharacterEncoding("utf-8");
		this.response.setContentType("application/json; charset=UTF-8");

		PrintWriter printWriter = null;
		try {
			printWriter = this.response.getWriter();
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
			return;
		}
		printWriter.write(object.toString());
		printWriter.flush();
		printWriter.close();
		logger.log(object.toString());
	}

}
